<template>
  <div class="upload-container">
    <div class="upload-area" @click="inputRef.click()">
      <input
        ref="inputRef"
        type="file"
        accept="image/*"
        @change="handleChange"
        class="file-input"
      />
      <div v-if="previewUrl" class="image-preview">
        <img :src="previewUrl" alt="Preview" class="preview-image" />
      </div>
      <div v-else class="upload-hint">点击上传图片</div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { uploadFile } from '@/API/upload.ts'
import { ElMessage } from 'element-plus'

const props = defineProps({ modelValue: String })
const emit = defineEmits(['update:modelValue'])

const inputRef = ref()
const previewUrl = ref('')

watch(() => props.modelValue, (val) => {
  if (val) previewUrl.value = val.startsWith('http') ? val : `http://localhost:3000${val}`
}, { immediate: true })

const handleChange = async () => {
  const file = inputRef.value.files[0]
  if (!file) return

  previewUrl.value = URL.createObjectURL(file)


  const formData = new FormData()
  formData.append('file', file)

  try {
    const res = await uploadFile(formData)
    if (res.code === 200) {
      emit('update:modelValue', res.data.url)
      ElMessage.success('上传成功')
      console.log('上传成功:', res.data.url)
    } else {
      throw new Error(res.msg)
    }
  } catch (err) {
    ElMessage.error(err.message || '上传失败')
    previewUrl.value = props.modelValue || ''
  }
}
</script>

<style scoped>
.upload-container {
  display: inline-block;
}
.upload-area {
  width: 240px;
  height: 120px;
  background-color: #f3f4f6;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  position: relative;
}
.file-input {
  position: absolute;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}
.image-preview {
  width: 100%;
  height: 100%;
}
.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.upload-hint {
  color: #6b7280;
  font-size: 14px;
}
</style>